package org.vaadinetherealintegration.client.example3;

import java.util.ArrayList;
import com.google.gwt.dom.client.NativeEvent;

import etrl.core.EventListener;
import etrl.core.Geode;
import etrl.core.Group;
import etrl.core.Transform;
import etrl.core.Viewer;
import etrl.core.Viewer.IntersectionSort;
import etrl.geometry.LineSegmentIntersector;
import etrl.vecmath.Vector3f;
import etrl.vecmath.Vector4f;

public class Picker implements EventListener
{
	private Viewer _viewer;
	private Group _root;

	private float _mX, _mY;
	
	public Picker(Viewer viewer, Group root)
	{
		_viewer = viewer;
		_root = root;
	}

	
	public void onMouseDown(NativeEvent event)
	{
		if(event.getButton() == NativeEvent.BUTTON_LEFT)
		{
			_mX = event.getClientX() - _viewer.getCanvas().getAbsoluteLeft();
			_mY = event.getClientY() - _viewer.getCanvas().getAbsoluteTop();
		}
	}

	
	public void onMouseUp(NativeEvent event)
	{
		if(event.getButton() == NativeEvent.BUTTON_LEFT)
		{
			// Get mouse coordinates in canvas space
			int x = event.getClientX() - _viewer.getCanvas().getAbsoluteLeft();
			int y = event.getClientY() - _viewer.getCanvas().getAbsoluteTop();
			
			if(_mX == x && _mY == y)
				pick(x,y);
		}
	}

	
	public void onMouseMove(NativeEvent event)
	{
		// TODO Auto-generated method stub
		
	}

	
	public void onMouseOut(NativeEvent event)
	{
		// TODO Auto-generated method stub
		
	}

	
	public void onMouseWheel(NativeEvent event)
	{
		// TODO Auto-generated method stub
		
	}

	
	public void onKeyDown(NativeEvent event)
	{
		// TODO Auto-generated method stub
		
	}

	
	public void onKeyUp(NativeEvent event)
	{
		// TODO Auto-generated method stub
		
	}

	
	public void onFrameEvent()
	{
		// TODO Auto-generated method stub
		
	}
	
	private void pick(int x, int y)
	{
		Vector4f start = new Vector4f();
		Vector4f end = new Vector4f();
		ArrayList <LineSegmentIntersector.Intersection> intersections = _viewer.intersects(x, y, start, end, IntersectionSort.CRESCENT_DISTANCE_SORT);
		
		// Get the first intersection point
		if(intersections.size() > 0)
		{
			LineSegmentIntersector.Intersection nearest = intersections.get(0);
			Vector4f I = nearest._worldIntersectionPoint;
			
			// draw a small sphere to intersection point
			Geode charGeode = new Geode();
			charGeode.addDrawable(new Character());
			
			Transform charTransform = new Transform();
			charTransform.addChild(charGeode);
			charTransform.setPosition(new Vector3f(I.x, I.y, I.z));
			charTransform.setUniformScale(0.2f);
			
			_root.addChild(charTransform);
		}
	}
}
